<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" v-show="showSearch" :inline="true"
      label-width="68px">
      <!-- <el-form-item label="地市主管" prop="preBec">
        <el-select v-model="queryParams.preBec" placeholder="请选择地市主管" clearable
          style="width: 220px">
          <el-option v-for="item in preBecSel" :key="item.id" :label="item.accountName"
            :value="item.id" />
        </el-select>
      </el-form-item> -->
      <el-form-item label="配送专员" prop="attache">
        <el-input v-model="queryParams.attache" placeholder="请输入配送专员" clearable
          style="width: 220px" />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd(1,'')"
          v-hasPermi="['delivery:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="View" @click="examineAll"
          v-hasPermi="['delivery:all']">全部区域</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <!-- 表格数据 -->
    <el-table v-loading="loading" :data="roleList" :max-height="tableHeight">
      <el-table-column label="地市主管" prop="managerName" :show-overflow-tooltip="true" />
      <el-table-column label="配送专员" prop="accountName" :show-overflow-tooltip="true" />
      <el-table-column label="电话" prop="phone" :show-overflow-tooltip="true" />
      <el-table-column label="区域名称" prop="districtName" :show-overflow-tooltip="true" />
      <el-table-column label="区域范围" prop="districtName" :show-overflow-tooltip="true">
        <template #default="scope">
          <el-button type="primary" text @click="examineMap(scope.row)">查看地图</el-button>
        </template>
      </el-table-column>
      <el-table-column label="操作" :show-overflow-tooltip="true">
        <template #default="scope">
          <!-- <el-tooltip content="修改" placement="top">
            <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
              v-hasPermi="['delivery:edit']"
              :disabled='scope.row.userType ==11?true:false'></el-button>
          </el-tooltip> -->
          <el-tooltip content="删除" placement="top">
            <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
              v-hasPermi="['delivery:delete']"
              :disabled='scope.row.userType ==11?true:false'></el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" @pagination="getList" />

    <el-drawer v-model="drawerMap" size='90%' :direction="direction" :before-close="handleClose"
      :close-on-click-modal='false' :show-close="false">
      <map-S @load-data="loadData" ref="userDialogRef" v-if="drawerMap" />
      <template #header="{ close, titleClass }">
        <h4 :class="titleClass">{{titleMap}}</h4>
        <el-button type="danger" @click="close">
          <el-icon class="el-icon--left">
            <CircleCloseFilled />
          </el-icon>
          关闭
        </el-button>
      </template>
    </el-drawer>
  </div>
</template>

<script setup name="Attache">
const { proxy } = getCurrentInstance();
import mapS from "./map/map";
import { ElMessage } from "element-plus";
import {
  beChargeAcc,
  preBecOSel,
  coordinates,
  delArea,
  UnderAccArea,
  examineAllArea,
} from "@/api/director/attache";
import useUserStore from "@/store/modules/user";
import { ref, onMounted, onUnmounted } from "vue";
const userStore = useUserStore();
const direction = ref("rtl");
const drawerMap = ref(false);
const searchSta = ref(false);
const showSearch = ref(true);
const loading = ref(true);
const total = ref(0);
const roleList = ref([]);
const titleMap = ref("新增专员");
const userDialogRef = ref("");
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 50,
    //  搜索条件
    // preBec: undefined,
    attache: undefined,

    userType: userStore.userDta.userType,
    id: userStore.userDta.id,
    shopId: userStore.userDta.shopId,
  },
  preBecSel: [],
  coordinatesList: [],
  examineMapSta: false,
  mapSelFals: false,
});
const {
  queryParams,
  form,
  preBecSel,
  coordinatesList,
  examineMapSta,
  mapSelFals,
} = toRefs(data);

// 动态计算表格高度
const queryRef = ref(null);
const tableHeight = ref("calc(100vh - 380px)"); // 假设顶部保留200px
watch(
  () => showSearch.value,
  (newValue) => {
    if (newValue) {
      if (queryRef.value.$el.offsetHeight == 0) {
        setTimeout(() => {
          let hight = 230 + queryRef.value.$el.offsetHeight + "px";
          tableHeight.value = `calc(100vh - ` + hight + `)`;
        }, 200);
      }
    } else {
      tableHeight.value = "calc(100vh - 230px)";
    }
  },
  { deep: true }
);
function handleResize() {
  let hight = 230 + queryRef.value.$el.offsetHeight + "px";
  tableHeight.value = `calc(100vh - ` + hight + `)`;
}
onMounted(async () => {
  await nextTick();
  let hight = 230 + queryRef.value.$el.offsetHeight + "px";
  tableHeight.value = `calc(100vh - ` + hight + `)`;
  window.addEventListener("resize", handleResize);
});
// 移除事件监听器以防止内存泄漏
onUnmounted(() => {
  window.removeEventListener("resize", handleResize);
});

provide(
  //若直接写state.myData无效，需加computed
  "preBecList",
  computed(() => data.preBecSel)
);
provide(
  //若直接写state.myData无效，需加computed
  "coordinatesList",
  computed(() => data.coordinatesList)
);
// 搜索
function handleQuery() {
  if (
    queryParams.value.attache == undefined ||
    queryParams.value.attache == ""
  ) {
    ElMessage({
      message: "请输入配送专员",
      type: "warning",
      duration: 2 * 1000,
    });
    return false;
  }
  searchSta.value = true;
  getList();
}
//重置
function resetQuery() {
  searchSta.value = false;
  queryParams.value.attache = undefined;
  getList();
}

function getList() {
  let userData = queryParams.value;
  let dataUser = {
    page: userData.pageNum,
    limit: userData.pageSize,
  };
  if (userData.userType == 11) {
    dataUser.shopId = userData.shopId;
  } else {
    dataUser.id = userData.id;
  }
  if (searchSta.value) {
    dataUser.staffName = queryParams.value.attache;
  }
  loading.value = true;
  beChargeAcc(dataUser)
    .then((res) => {
      roleList.value = res.data;
      total.value = res.count;
      loading.value = false;
    })
    .catch((r) => {
      loading.value = false;
    });
}
provide(
  //若直接写state.myData无效，需加computed
  "examineMapSta",
  computed(() => data.examineMapSta)
);
provide(
  //若直接写state.myData无效，需加computed
  "mapSelFals",
  computed(() => data.mapSelFals)
);
// 查看地图
function examineMap(row) {
  examineMapSta.value = false;
  titleMap.value = "查看区域";
  handleAdd(2, row.accountId);
}
// 查看全部区域
function examineAll() {
  drawerMap.value = true;
  examineAllArea({ shopId: userStore.userDta.shopId }).then((res) => {
    const resList = [];
    for (let i = 0; i < res.data.length; i++) {
      resList.push({
        accountName: res.data[i].accountName,
        deliveryScope: [],
        deliveryScopexy: [],
        districtName: res.data[i].districtName,
      });
      for (let j = 0; j < res.data[i].deliveryScope.length; j++) {
        resList[i].deliveryScope.push([
          res.data[i].deliveryScope[j].longitude,
          res.data[i].deliveryScope[j].latitude,
        ]);
        resList[i].deliveryScopexy.push({
          y: res.data[i].deliveryScope[j].longitude,
          x: res.data[i].deliveryScope[j].latitude,
        });
      }
    }
    mapSelFals.value = !mapSelFals.value;
    coordinatesList.value = resList;
  });
}
// 新增
async function handleAdd(sta, id) {
  coordinatesList.value = [];
  if (sta == 1) {
    await preBecOSelPOST();
    titleMap.value = "新增专员";
    examineMapSta.value = true;
  }
  drawerMap.value = true;
  if (sta == 2) {
    coordinates({ shopId: userStore.userDta.shopId, accountId: id }).then(
      (res) => {
        const resList = [];
        for (let i = 0; i < res.data.length; i++) {
          resList.push({
            accountName: res.data[i].accountName,
            deliveryScope: [],
            deliveryScopexy: [],
            districtName: res.data[i].districtName,
          });
          for (let j = 0; j < res.data[i].deliveryScope.length; j++) {
            resList[i].deliveryScope.push([
              res.data[i].deliveryScope[j].longitude,
              res.data[i].deliveryScope[j].latitude,
            ]);
            resList[i].deliveryScopexy.push({
              y: res.data[i].deliveryScope[j].longitude,
              x: res.data[i].deliveryScope[j].latitude,
            });
          }
        }
        mapSelFals.value = !mapSelFals.value;
        coordinatesList.value = resList;
      }
    );
  }
}

// 修改
function handleUpdate(row) {}
// 删除
function handleDelete(row) {
  proxy.$modal
    .confirm('是否确认删除"' + row.accountName + '"配送专员？')
    .then(function () {
      return delArea({ id: row.id });
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}
// 关闭地图
function handleClose() {
  // drawerMap.value = false;
  userDialogRef.value.handleCloseMap();
}
function loadData(value) {
  if (value == "关闭right") {
    drawerMap.value = false;
  } else if (value == "关闭") {
    coordinatesList.value = [];
    handleClose();
    getList();
  } else {
    if (value == "") {
      mapSelFals.value = !mapSelFals.value;

      coordinatesList.value = [];
    } else {
      UnderAccArea({ managerId: value }).then((res) => {
        const resList = [];
        for (let i = 0; i < res.data.length; i++) {
          resList.push({
            accountName: res.data[i].accountName,
            deliveryScope: [],
            deliveryScopexy: [],
            districtName: res.data[i].districtName,
          });
          for (let j = 0; j < res.data[i].deliveryScope.length; j++) {
            resList[i].deliveryScope.push([
              res.data[i].deliveryScope[j].longitude,
              res.data[i].deliveryScope[j].latitude,
            ]);
            resList[i].deliveryScopexy.push({
              y: res.data[i].deliveryScope[j].longitude,
              x: res.data[i].deliveryScope[j].latitude,
            });
          }
        }
        mapSelFals.value = !mapSelFals.value;

        coordinatesList.value = resList;
      });
    }
  }
}
// 地市主管
const preBecOSelPOST = async () => {
  let shopIds = {
    shopId: userStore.userDta.shopId,
  };
  if (userStore.userDta.userType != 11) {
    shopIds.managerId = userStore.userDta.id;
  }
  await preBecOSel(shopIds).then((res) => {
    console.log(res, ";;;;;;;;;;;;;;;;;;;;;;;;;;;");
    preBecSel.value = res.data;
  });
};
// preBecOSelPOST();
getList();
</script>

<style scoped lang="scss"></style>
